﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Win32;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;

namespace ExtractRegisteryToXml
{
    public class ExtractRegistery
    {

        public static XmlNode readRegisteryKey(RegistryKey key,XmlDocument xDoc)
        {
            XmlNode xRet = xDoc.CreateElement ("RegistryKey");
            XmlAttribute xAttr = xDoc.CreateAttribute("PathOfTheKey_Main");
            xRet.Attributes.Append(xAttr);
            xAttr.Value = key.ToString();
            string[] strValueNames = key.GetValueNames();
            //xAttr = xDoc.CreateAttribute("DefaultValue_Main");
            //xRet.Attributes.Append(xAttr);
            //try
            //{
            //    xAttr.Value = key.GetValue(null).ToString();
            //}
            //catch
            //{
            //    xAttr.Value = "";
            //}


            foreach (string name in strValueNames)
            {
                string modName;
                if (name == "")
                    modName = "Default_Name";
                else
                    modName = name;
                xAttr = xDoc.CreateAttribute(normalizeName(modName));
                xRet.Attributes.Append(xAttr);
                xAttr.Value =  key.GetValue(name).ToString();
            }


            string[] strSubKeys = key.GetSubKeyNames();

            foreach (string name in strSubKeys)
            {
                RegistryKey sub = key.OpenSubKey(name);
                xRet.AppendChild(readRegisteryKey(sub, xDoc));
            }






            return xRet;
        }




        public static RegistryKey getMainKeyByName(string name)
        {
            switch (name.ToUpper())
            {
                case "HKEY_CLASSES_ROOT":
                    return Registry.ClassesRoot;
                    break;
                case "HKEY_CURRENT_USER":
                    return Registry.CurrentUser;
                    break;
                case "HKEY_LOCAL_MACHINE":
                    return Registry.LocalMachine;
                    break;
                case "HKEY_USERS":
                    return Registry.Users;
                    break;
                case "HKEY_CURRENT_CONFIG":
                    return Registry.CurrentConfig;
                    break;
                default :
                    return Registry.LocalMachine;
                    break;
                    
            }
        }


        public static string normalizeName(string strName)
        {
            string ret = null;

            Regex regNew = new Regex("[^0-9A-Za-z]+");
            ret = regNew.Replace(strName, "_");





            return ret;
        }

    }
}
